<template>
  <basic-container>
    <!--<el-button type="primary" @click="handleUpload">入库</el-button>-->

    <!-- 子组件 -->
    <viewpage ref="viewpage"></viewpage>
    <drawingdetail ref="drawingdetail"></drawingdetail>
    <uploadfile ref="uploadfile"></uploadfile>
   
    <el-container>
      <el-header style="margin-top: 10px;">
        <!--查询条件展示-->
        <el-form :inline="true" :model="formInline" class="demo-form-inline" size="small" ref="searchForm">
          <el-row>
            <el-col :span="6">
              <el-form-item label="设备代号" prop="drawingNumber">
                <el-input placeholder="设备代号" clearable v-model="formInline.drawingNumber"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="设备名称" prop="drawingName">
                <el-input placeholder="设备名称" clearable v-model="formInline.drawingName"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="设备材料" prop="material">
                <el-input placeholder="设备材料" clearable v-model="formInline.material"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="图纸备注" prop="remark">
                <el-select v-model="formInline.remark" placeholder="请选择图纸备注" clearable>
                  <el-option v-for="(item) in drawingRemarkList" :key="item.id" :label="item.dictValue"
                    v-bind:value="item.dictValue"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="特征值一" prop="characOne">
                <el-input placeholder="特征值一" clearable v-model="formInline.characOne"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="特征值二" prop="characTwo">
                <el-input placeholder="特征值二" clearable v-model="formInline.characTwo"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="特征值三" prop="characThree">
                <el-input placeholder="特征值三" clearable v-model="formInline.characThree"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="图纸类型" prop="drawingType">
                <el-select v-model="formInline.drawingType" placeholder="请选择图纸类型" clearable>
                  <el-option v-for="(item) in drawingTypeList" :key="item.id" :label="item.name"
                    v-bind:value="item.code"></el-option>
                </el-select>
              </el-form-item>
            </el-col>

          </el-row>
          <el-row>
            <el-col :span="9"></el-col>
            <el-col :span="7">
              <el-form-item>
                <el-button type="primary" size="small" icon="el-icon-search" @click="onSubmit">查询</el-button>
                <el-button type="primary" size="small" icon="el-icon-close" @click="onClean('searchForm')">重置
                </el-button>
              </el-form-item>
            </el-col>
            <el-col :span="8"></el-col>
          </el-row>
        </el-form>
      </el-header>
      <el-container style="margin-top: 90px;height: 550px;">
        <el-aside width="250px" style="margin-top: 45px;border: 2px solid #eee">
          <el-tree ref="tree" :data="treeData" highlight-current node-key="id" :props="defaultProps" lazy
            @node-click="handleNodeClick" :load="loadTreeNode"></el-tree>
        </el-aside>
        <el-main>
          <avue-crud :option="option" :table-loading="loading" :data="data" :page.sync="page"
            :permission="permissionList"  v-model="form" ref="crud" @row-update="handleEdit"
            @row-save="rowSave" @row-del="rowDel" @search-change="searchChange" @search-reset="searchReset"
            @selection-change="selectionChange" @current-change="currentChange" @size-change="sizeChange"
            @refresh-change="refreshChange" :row-class-name="tableRowClassName" @on-load="onLoad">
            <template slot-scope="scope" slot="menu" style="width: auto;">
              <el-button icon="el-icon-rank" size="small" type="text" @click.stop="handleImg(scope.row)">缩略图</el-button>
              <el-button v-if="scope.row.status != '2' || permission.attach_view" icon="el-icon-view" size="small" type="text" @click.stop="handleView(scope.row)">查 看
              </el-button>
              <el-button v-if="permission.attach_update" icon="el-icon-edit" size="small"
                v-show="scope.row.status != '2'" type="text" @click.stop="handleEdit(scope.row)">编 辑
              </el-button>
              <el-button icon="el-icon-download" size="small" type="text"
                @click.stop="handleLoad(scope.row,scope.index)">下 载</el-button>
            </template>
            
          </avue-crud>
        </el-main>
      </el-container>
    </el-container>
    <!--缩略图展示-->
    <el-dialog title="图片信息展示" append-to-body center :visible.sync="imgBox" width="40%">
      <el-form ref="imgInfo" :model="imgForm" label-width="80px" size="small">
        <el-form-item label="图片信息" prop="imgFiles" ref="imgElement">
          <el-upload style="display: inline-block" disabled class="avatar-uploader" action="#" ref="imgUpload"
            list-type="picture-card" :auto-upload="false" :file-list="imgFileList" accept=".png,.jpg,.jpeg,.gif"
            :on-preview="handlePictureCardPreview">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible" append-to-body>
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>

      </el-form>

    </el-dialog>
  </basic-container>

</template>

<script>
  import {
    remove, getDrawingInfo, add, update, getFileById, getLazyTree, getList,
    getDrawingTypeList, getDictValueList, getTreeList, getDrawingInfoByNodeId,
    getImgList
  } from "@/api/resource/attach";
  import { mapGetters } from "vuex";
  import viewpage from "@/views/drawing/viewpage";
  import drawingdetail from "@/views/drawing/drawingdetail";
  import uploadfile from "@/views/drawing/uploadfile";
  import {updateDrawingStatus} from "@/api/drawing/drawingupload";

  export default {
    components: { viewpage,drawingdetail,uploadfile },
    data() {
      return {
        // 展示图片信息
        imgBox: false,
        imgForm: {
          imgFiles: '',
        },
        imgFileList: [],
        dialogImageUrl: '',
        dialogVisible: false,
        // 搜索框中的值
        formInline: {
          drawingNumber: '',
          drawingName: '',
          material: '',
          drawingProperty: '',
          remark: '',
          characOne: '',
          characTwo: '',
          characThree: '',
          drawingType: '',
        },
        drawingTypeList: [],
        // 备注
        drawingRemarkList: [],
        // 树形结构
        treeData: [],
        defaultProps: {
          children: 'children',
          label: 'title',
          isLeaf: 'leaf'
        },
        // 右侧展示
        data: [],
        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          border: true,
          menuWidth: 200,
          // 关闭掉自带的菜单栏
          addBtn: false,
          delBtn: false,
          editBtn: false,
          refreshBtn: false,
          columnBtn: false,
          searchBtn: false,
          headerAlign: 'center',
          align: 'center',
          indexLabel: '序号',
          index: true,
          column: [
            {
              label: "代号",
              prop: "drawingNumber",
              overHidden: true,
              width: 110,
            },
            {
              label: "名称",
              prop: "drawingName",
              overHidden: true,
              width: 130,
            },
            {
              label: "图纸类型",
              prop: 'drawingTypeName',
              overHidden: true,
            },
            {
              label: "材料",
              prop: "material",

            },
            {
              label: "单重",
              prop: "singleWeight",
              rules: [{
                required: true,
                message: "请输入单重",
                trigger: "blur"
              }]
            },
            {
              label: "属性",
              prop: "drawingProperty",
            },
            {
              label: "备注",
              prop: "remark",
            },
            {
              label: "特征值一",
              prop: "characOne",

            },
            {
              label: "特征值二",
              prop: "characTwo",

            },
            {
              label: "特征值三",
              prop: "characThree",
            },
            {
              label: "图纸状态",
              type: "select",
              dicUrl: "/api/blade-system/dict/dictionary?code=drawingInfo_status",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              dataType: "number",
              prop: "status",
            },
            {
              label: "操作人",
              prop: "userAccount",
            },
            {
              label: "上传时间",
              prop: "createTime",
              width: 140,
              format: "yyyy-MM-dd hh:mm:ss",
            },
          ]
        },
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          // editBtn: this.vaildData(this.permission.attach_update)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      },
    },
    watch: {
    },
    created() {
      this.getDrawingTypeListFun();
      this.drawingTypeListFun();
      this.loading = false;
    },

    methods: {

      tableRowClassName({row, rowIndex}) {
        if(row.status == 2){
          return 'warning-row';
        }
        return '';
      },

      // 查看按钮事件
    /*   handleView(row) {
        this.$router.push({
          path: '/drawing/viewpage',
          query: {
            id: row.id,
          }
        })
      }, */
      handleView(row) {
        this.$nextTick(() => {
          this.loading = true;
          this.$refs.viewpage.initData();
          this.$refs.viewpage.setDrawId(row.id);
          this.$refs.viewpage.parentCreated();
          this.loading = false;
        })
      },
      // 编辑按钮的点击事件
      handleEdit(row) {
      /*   this.$router.push({
          path: '/drawing/drawingdetail',
          query: {
            id: row.id,
          }
        }) */
        this.$nextTick(() => {
          this.loading = true;
          this.$refs.drawingdetail.initData();
          this.$refs.drawingdetail.setDrawId(row.id);
          this.$refs.drawingdetail.parentCreated();
          this.loading = false;
        })
      },

       // 下载
       handleLoad(row) {
        // this.$router.push({
        //   path: '/drawing/upload',
        //   query: {
        //     id: row.id,
        //   }
        // })
        this.$nextTick(() => {
          this.loading = true;
          this.$refs.uploadfile.setDrawId(row.id);
          this.$refs.uploadfile.getDetail();
          this.loading = false;
        })
      },
      // 查看图片回显信息
      handleImg(row) {
        this.imgBox = true;
        getImgList(row.id).then((res) => {
           this.imgFileList = [];
          let attach = res.data.data;
          for (let i = 0; i < attach.length; i++) {
            this.imgFileList.push({ "url": attach[i].link, "name": attach[i].originalName });
          }
        })
      },

      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },

      // 获取数据库中所有的图纸备注信息 标准件、采购件
      drawingTypeListFun() {
        getDictValueList("drawing_remark").then(res => {
          this.drawingRemarkList = res.data.data;
        })
      },
      // 查询按钮时间
      onSubmit() {
        let searchObj = this.getParm();
        this.loading = true;
        getList(this.page.currentPage, this.page.pageSize, searchObj).then((res) => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
        });
        getTreeList(searchObj).then((res) => {
          this.treeData = res.data.data.map(item => {
            return {
              ...item,
              leaf: !item.hasChildren
            }
          });
        });
      },

      getParm(){
        let drawingNumber = { "drawingNumber": this.formInline.drawingNumber };
        let drawingName = { "drawingName": this.formInline.drawingName };
        let material = { "material": this.formInline.material };
        let drawingProperty = { "drawingProperty": this.formInline.drawingProperty };
        let remark = { "remark": this.formInline.remark };
        let characOne = { "characOne": this.formInline.characOne };
        let characTwo = { "characTwo": this.formInline.characTwo };
        let characThree = { "characThree": this.formInline.characThree };
        let drawingType = { "drawingType": this.formInline.drawingType };
        let searchObj = Object.assign(drawingNumber, drawingName, material, drawingProperty, remark, characOne, characTwo, characThree, drawingType);
        return searchObj;
      },
      // 重置
      onClean(formName) {
        this.$refs[formName].resetFields();
        //测试生成对应的树结构,无用,只是为了不走流程测试用
        // updateDrawingStatus('1483723220031930369', 3);
      },
      // 获取图纸类型中的值
      getDrawingTypeListFun() {
        getDrawingTypeList().then(res => {
          this.drawingTypeList = res.data.data;
        })
      },

      // 动态加载
      loadTreeNode(node, resolve) {
        const parentCode = (node.level === 0) ? 0 : node.data.infoId;
        // if (node.level ===0) {
        //   getLazyTree(parentCode).then(res => {
        //     resolve(res.data.data);
        //   })
        // }
        if (node.level > 0) {
          getLazyTree(parentCode, parentCode).then((res) => {
            const nodeData = res.data.data[0].children;
            resolve(nodeData.map(item => {
              return {
                ...item,
                leaf: !item.hasChildren
              }
            }));
          })
        }
      },

      // 加载树形结构节点 右侧表格中的数据
      handleNodeClick(data) {
        this.data = [];
        getDrawingInfoByNodeId(data.infoId).then(res => {
          this.data.push(res.data.data);
        })
      },

      // handleUpload() {
      //    let id = '1405094299258871810';
      //   getFileById(id).then((res) => {
      //     console.log("res----->"+JSON.stringify(res));
      //   })
      // },

      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      rowSave(row, done, loading) {
        add(row).then((res) => {
          // 获取新增数据的相关字段
          const data = res.data.data;
          row.id = data.id;
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          // 数据回调进行刷新
          done(row);
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          // 数据回调进行刷新
          done(row);
        }, error => {
          window.console.log(error);
          loading();
        });
      },

      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },

      beforeOpen(done, type) {
        if (["add", "edit"].includes(type)) {
          this.initData();
        }
        if (["edit", "view"].includes(type)) {
          getDrawingInfo(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },

      searchReset() {
        this.query = {};
        this.parentId = 0;
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.parentId = '';
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage) {
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize) {
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        //let searchObj = this.getParm();
        getList(this.page.currentPage, this.page.pageSize, params).then((res) => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
        });
        getTreeList(params).then((res) => {
          this.treeData = res.data.data.map(item => {
            return {
              ...item,
              leaf: !item.hasChildren
            }
          });
          this.loading = false;
        });
        
      },
    }
  };
</script>

<style>
  .el-scrollbar__wrap {
    overflow-x: hidden !important;
  }
  .el-table .warning-row {
    background: #faeacc;
  }
  .warning-row td:nth-child(2) span {
    text-decoration: line-through;
  }
</style>